package net.bio;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.Executors;

/**
 * @author 王霄
 * @date 2021/8/21 15:36
 */
public class BioServer {

    public static void main(String[] args) throws IOException {
        var executor = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("socket服务端启动成功,端口8888");
        while (true) {
            var socket = serverSocket.accept();
            System.out.println("连接到一个客户端：" + socket.getLocalAddress());
            executor.execute(() -> handle(socket));
        }
    }

    private static void handle(Socket socket) {
        try (var inputStream = socket.getInputStream()) {
            var bytes = new byte[1024];
            while (true) {
                if (inputStream.read(bytes) != -1) {
                    System.out.printf("当前线程：%s,发送内容：%s%n", Thread.currentThread().getId(),
                            new String(bytes, StandardCharsets.UTF_8));
                }
            }
        } catch (IOException ignored) {
        }
    }
}
